/*
 * Copyright 2016 Yan Zhenjie
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mingmen.canting.caigourenyuan;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.mingmen.canting.R;
import com.mingmen.canting.adapter.ImagePickerAdapter;
import com.mingmen.canting.adapter.ReasonHistoryAdapter;
import com.mingmen.canting.adapter.TuiHuoReasonAdapter;
import com.mingmen.canting.adapter.TuihuoListAdapter;
import com.mingmen.canting.definerecycleview.SwipeRecyclerView;
import com.mingmen.canting.http.MyOkhttp;
import com.mingmen.canting.http.callback.StringCallback;
import com.mingmen.canting.httpconfig.AppConfig;
import com.mingmen.canting.httpconfig.HttpResponse;
import com.mingmen.canting.imageloader.GlideImageLoader;
import com.mingmen.canting.immersionbar.ImmersionBar;
import com.mingmen.canting.label.recycler.OnItemClickListener;
import com.mingmen.canting.model.PicSendModel;
import com.mingmen.canting.model.TuiHuoDetailModel;
import com.mingmen.canting.model.TuiHuoReason;
import com.mingmen.canting.util.GsonUtil;
import com.mingmen.canting.util.MyStringUtils;
import com.mingmen.canting.util.SharePreferenceUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Response;


/**
 * <p>
 * ListView形式的侧滑菜单，支持横向和竖向的。
 * </p>
 * Created by Yan Zhenjie on 2016/7/27.
 */
public class TuiHuoActivity extends Activity implements ImagePickerAdapter.OnRecyclerViewItemClickListener {

    @BindView(R.id.text_return)
    TextView textReturn;
    @BindView(R.id.linear_return)
    LinearLayout linearReturn;
    @BindView(R.id.text_center)
    TextView textCenter;
    @BindView(R.id.img_right)
    ImageView imgRight;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.mToolbar)
    Toolbar mToolbar;

    @BindView(R.id.recycle_queren)
    SwipeRecyclerView recycle_queren;
    LinearLayoutManager layoutManager;

    List<String> mylist = new ArrayList<>();
    TuiHuoReasonAdapter linkLabelAdapter;
    GridLayoutManager gridLayoutManager;
    private ImagePicker imagePicker;
    @BindView(R.id.img_select)
    ImageView img_select;
    ArrayList<ImageItem> images = new ArrayList<>();

    @BindView(R.id.layout_pic)
    RecyclerView layout_pic;

    GridLayoutManager gridLayoutManager1;
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;

    private ImagePickerAdapter adapter;
    private ArrayList<ImageItem> selImageList = new ArrayList<>(); //当前选择的所有图片
    private int maxImgCount = 8;               //允许选择图片最大数
    String token;
    List<TuiHuoReason.DataBean> dataBeanList = new ArrayList<>();
    String billId;
    @BindView(R.id.btn_genghuan)
    Button btn_genghuan;

    @BindView(R.id.recycleview_shop)
    RecyclerView recycleview_shop;
    LinearLayoutManager linearLayoutManager;

    TuihuoListAdapter tuihuoListAdapter;

    @BindView(R.id.edit_reason)
    EditText edit_reason;
    String getBillDetailIds;
    List<TuiHuoDetailModel.DataBean> tuihuoDataList = new ArrayList<>();
    String supplierId;


    public static Set<Integer> positionSet = new HashSet<>();
    private boolean selectMode = true; //选择模式 多选或者单选  true  多选
    private String checktypeId = ""; //记录选择种类 多种类以" ,"分开
    public Set<String> checkTYpeNameSet = new HashSet<>();

    private ReasonHistoryAdapter reasonHistoryAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tuihuo);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        textCenter.setText("退货原因");
        ImmersionBar.with(this).titleBar(mToolbar)
                .navigationBarColor(R.color.black).init();
        token = (String) SharePreferenceUtil.get(this, "token", "");
        billId = getIntent().getStringExtra("billId");
        supplierId = getIntent().getStringExtra("supplierId");
        getBillDetailIds = getIntent().getStringExtra("getBillDetailIds");


        gridLayoutManager = new GridLayoutManager(this, 3);
        recycle_queren.setLayoutManager(gridLayoutManager);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);

        recycle_queren.setLayoutManager(gridLayoutManager);
//        recycle_queren.setScrollEnabled(false);


        initData();
        initListener();

        gridLayoutManager1 = new GridLayoutManager(this, 3);
        layout_pic.setLayoutManager(gridLayoutManager1);

        adapter = new ImagePickerAdapter(this, selImageList, maxImgCount);
        adapter.setOnItemClickListener(this);

        layout_pic.setLayoutManager(new GridLayoutManager(this, 4));
        layout_pic.setHasFixedSize(true);
        layout_pic.setAdapter(adapter);
        DividerItemDecoration divider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(this, R.drawable.custom_divider));
        layout_pic.addItemDecoration(divider);
        recycle_queren.addItemDecoration(divider);
        linearLayoutManager = new LinearLayoutManager(this);
        recycleview_shop.setLayoutManager(linearLayoutManager);
        tuihuoListAdapter = new TuihuoListAdapter(this, tuihuoDataList);
        recycleview_shop.setAdapter(tuihuoListAdapter);
        recycleview_shop.setNestedScrollingEnabled(false);
        HttpResponse.getCommodityByBillDetailId(token, getBillDetailIds, new StringCallback(this) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                TuiHuoDetailModel tuiHuoDetailModel = new TuiHuoDetailModel();
                tuiHuoDetailModel = GsonUtil.GsonToBean(s, TuiHuoDetailModel.class);
                tuihuoDataList.addAll(tuiHuoDetailModel.getData());
                tuihuoListAdapter.setDataList(tuihuoDataList);
            }
        });
        imageCreate();
        for (int i = 0; i < 5; i++) {
            mylist.add("Item" + i);
        }
        linkLabelAdapter = new TuiHuoReasonAdapter(this, dataBeanList);
    }
    private void initData() {
        reasonHistoryAdapter = new ReasonHistoryAdapter(TuiHuoActivity.this, dataBeanList);
        recycle_queren.setAdapter(reasonHistoryAdapter);
        HttpResponse.listCancelReason(token, "5", new StringCallback(this) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.d("TuihuoActivity", s);

                TuiHuoReason tuiHuoReason = new TuiHuoReason();
                tuiHuoReason = GsonUtil.GsonToBean(s, TuiHuoReason.class);
                dataBeanList = tuiHuoReason.getData();
                reasonHistoryAdapter.setDataList(dataBeanList);
            }
        });
    }

    private void initListener() {
        reasonHistoryAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void OnItemClick(View view, int position) {
                addOrRemove(position);
            }
            @Override
            public void OnItemLongClick(View view, int position) {
            }
        });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();

    }


    @OnClick({R.id.text_return, R.id.linear_return, R.id.img_select, R.id.btn_genghuan})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.text_return:
            case R.id.linear_return:
                finish();

                break;
            case R.id.btn_register:
                break;
            case R.id.img_select:
                intent = new Intent(this, ImageGridActivity.class);
                intent.putExtra(ImageGridActivity.EXTRAS_IMAGES, images);
                //ImagePicker.getInstance().setSelectedImages(images);
                startActivityForResult(intent, 100);
                break;
            case R.id.btn_genghuan:

                if (TextUtils.isEmpty(edit_reason.getText().toString())) {
                    Toast.makeText(this, "请输入退货原因", Toast.LENGTH_SHORT).show();
                } else {
                    String mystrPic= MyStringUtils.returnStringBuffer(pictureList);
                    intent = new Intent(TuiHuoActivity.this, TuiHuoDialogActivity.class);
                    intent.putExtra("billId", billId);
                    intent.putExtra("supplierId", supplierId);
                    intent.putExtra("cancelReason", edit_reason.getText().toString());
//                    intent.putExtra("pictureList", pictureList.toString());
                    intent.putExtra("pictureList", mystrPic);
                    intent.putExtra("getBillDetailIds", getBillDetailIds);

                    startActivity(intent);
                }

                break;
        }
    }

    public void imageCreate() {
        imagePicker = ImagePicker.getInstance();

        imagePicker.setImageLoader(new GlideImageLoader());
        imagePicker.setMultiMode(true);
        imagePicker.setShowCamera(true);
        imagePicker.setCrop(false);
        imagePicker.setSaveRectangle(true);
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);
        Integer width = Integer.valueOf(280);
        Integer height = Integer.valueOf(280);
        width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, width, getResources().getDisplayMetrics());
        height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, height, getResources().getDisplayMetrics());
        imagePicker.setFocusWidth(width);
        imagePicker.setFocusHeight(height);
        imagePicker.setOutPutX(Integer.valueOf(800));
        imagePicker.setOutPutY(Integer.valueOf(800));
    }

    List<File> myfile = new ArrayList<>();
    File file;
    String path;
    List<String> pictureList = new ArrayList<>();

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                }
                for (int i = 0; i < images.size(); i++) {
                    path = images.get(i).path;
                    file = new File(path);
                    myfile.add(file);
                }


            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                    selImageList.clear();
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                    for (int i = 0; i < images.size(); i++) {
                        path = images.get(i).path;
                        file = new File(path);
                        myfile.add(file);
                    }
                }
            }
        }

//        MyOkhttp.post("http://192.168.3.18:9001/system/upload/img")
        MyOkhttp.post(AppConfig.IMGURL + "/system/upload/img")
                .params("token", "123")
                .addFileParams("file", myfile)
                .execute(new StringCallback(this) {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.d("DKkdkdkd", s);
                        PicSendModel picSendModel = new PicSendModel();
                        picSendModel = GsonUtil.GsonToBean(s, PicSendModel.class);
                        pictureList = picSendModel.getData();

                    }
                });


    }

    @Override
    public void onItemClick(View view, int position) {

        switch (view.getId()) {
            case R.id.img_cel:
                selImageList.remove(position);
                adapter.setImages(selImageList);
                adapter.notifyDataSetChanged();
                break;
            case R.id.iv_img:
                switch (position) {
                    case IMAGE_ITEM_ADD:
                        ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                        Intent intent1 = new Intent(TuiHuoActivity.this, ImageGridActivity.class);
//                                intent1.putExtra(ImageGridActivity.EXTRAS_IMAGES,images);
                        startActivityForResult(intent1, REQUEST_CODE_SELECT);
                        break;
                    default:
                        //打开预览
                        Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
                        intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                        intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                        intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                        startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                        break;
                }

                break;

        }

    }

    public void onEventMainThread(Integer a) {
        if (a == 4) {
            finish();
        }
    }


    private void addOrRemove(int position) {
        if (positionSet.contains(position)) {
            // 如果包含，则撤销选择
            positionSet.remove(position);
            checkTYpeNameSet.remove(dataBeanList.get(position).getMark());
        } else {
            // 如果不包含，则添加
            positionSet.add(position);
            checkTYpeNameSet.add(dataBeanList.get(position).getMark());
        }
        if (positionSet.size() == 0) {
            // 如果没有选中任何的item，则退出多选模式
            reasonHistoryAdapter.notifyDataSetChanged();
            selectMode = false;
        } else {
            // 更新列表界面，否则无法显示已选的item
            reasonHistoryAdapter.notifyDataSetChanged();
        }

        Log.e("info", positionSet.toString());
        if (checkTYpeNameSet.size() == 0) {
            edit_reason.setText("");
        } else {
            edit_reason.setText(checkTYpeNameSet.toString());
        }

//        Toast.makeText(TuiHuoActivity.this, checkTYpeNameSet.toString(), Toast.LENGTH_SHORT).show();
    }


}